using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Linq;
using System.Data.Linq.Mapping;

namespace ClubWebsite
{
    public partial class AddClub : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Ensure the user is logged in
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                pnlAddClub.Visible = false;
                pnlNotLoggedIn.Visible = true;
            }
            else
            {
                pnlAddClub.Visible = true;
                pnlNotLoggedIn.Visible = false;
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            // Validation
            valClubName.Validate();
            if (!valClubName.IsValid)
            {
                return;
            }

            // Save the changes
            string uniqueTextForURLs = txtClubName.Text.Replace(" ", "").ToLower();
            using (MainDataClassesDataContext databaseDataContext = Functions.GetDatabaseDataContext())
            {
                DBClub club = new DBClub();
                club.ID = Guid.NewGuid();
                club.Name = txtClubName.Text.Trim();
                club.DefaultPageID = Guid.Empty;
                club.UniqueTextForURLs = uniqueTextForURLs;
                var settingsProperties = databaseDataContext
                    .Settings
                    .Select(s => new { ClubDefaultTemplateHTML = s.ClubDefaultTemplateHTML, ClubDefaultCSS = s.ClubDefaultCSS })
                    .Single();
                club.TemplateHTML = settingsProperties.ClubDefaultTemplateHTML;
                club.CSS = settingsProperties.ClubDefaultCSS;
                databaseDataContext.DBClubs.InsertOnSubmit(club);

                // The club mest be added now because of the circular reference with the pages table
                databaseDataContext.SubmitChanges();
                club.DefaultPageID = Guid.NewGuid();
                club.TemplateHTML = club.TemplateHTML.Replace("page=home", String.Format("page={0}", club.DefaultPageID));

                // Create the entry for the default page to use
                Entry entry = new Entry();
                entry.ID = Guid.NewGuid();
                entry.ClubID = club.ID;
                entry.HTML = String.Format("Welcome to the website for {0}.<br/><br/>If you're logged in, click the Modify button above to change the text on this page.<br/>If you're not logged in, click Login at the very top of this page.", txtClubName.Text.Trim());
                databaseDataContext.Entries.InsertOnSubmit(entry);

                // Create the default page for the club
                DBPage page = new DBPage();
                page.ID = club.DefaultPageID;
                page.ClubID = club.ID;
                page.Title = "Home";
                page.UniqueTextForURLs = "home";
                page.HTML = String.Format("[entry={0}]", entry.ID.ToString());
                databaseDataContext.DBPages.InsertOnSubmit(page);
                
                // Add the user to the list of users allowed to edit the club
                UsersClub usersClub = new UsersClub();
                usersClub.ClubID = club.ID;
                usersClub.UserID = new Guid(HttpContext.Current.User.Identity.Name);
                databaseDataContext.UsersClubs.InsertOnSubmit(usersClub);

                // Save the changes to the database
                databaseDataContext.SubmitChanges();
            }

            // Go to the new page
            Response.Redirect("/" + uniqueTextForURLs + "/home/");
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            // Go back a page
            Response.Redirect(Request.UrlReferrer.ToString());
        }

        protected void valClubName_ServerValidate(object source, ServerValidateEventArgs args)
        {
            // Required
            if (txtClubName.Text.Trim().Length == 0)
            {
                valClubName.ErrorMessage = "An entry is required";
                args.IsValid = false;
                return;
            }

            // Max length
            int maxLength = typeof(DBClub).GetProperties()
                .Where(p => p.Name.ToLower() == "name")
                .Select(p => Functions.GetColumnSize((ColumnAttribute)p.GetCustomAttributes(typeof(ColumnAttribute), false).First()))
                .First();
            if (txtClubName.Text.Trim().Length > maxLength)
            {
                valClubName.ErrorMessage = String.Format("The entry cannot be more than {0} characters", maxLength);
                args.IsValid = false;
                return;
            }

            // Unique
            bool nameInUse = Functions.GetDatabaseDataContext()
                .DBClubs
                .Any(c => c.Name.ToLower() == txtClubName.Text.ToLower());
            if (nameInUse)
            {
                valClubName.ErrorMessage = "This name is already taken";
                args.IsValid = false;
                return;
            }
        }
    }
}